package com.dwj.auto.comment.common.security;

import com.dwj.auto.comment.common.response.Response;
import com.dwj.auto.comment.common.response.ResultEnum;
import com.dwj.auto.comment.common.security.jwt.JWTTokenHelper;
import com.dwj.auto.comment.common.utils.JSONResponseUtils;
import com.dwj.auto.comment.dao.entity.User;
import com.dwj.auto.comment.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @author: dangweijian
 * @description: 登录成功处理类
 * @create: 2020-07-09 14:58
 **/
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JWTTokenHelper jwtTokenHelper;
    @Autowired
    private IUserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        User user = (User) authentication.getPrincipal();
        String token = jwtTokenHelper.createToken(user);
        user.setLoginToken(token);
        user.setLastLoginTime(new Date());
        userService.updateById(user);
        JSONResponseUtils.build(response, Response.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), token));
    }
}
